package com.gopay.webtest.controller.entrustpay;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.webtest.controller.base.BaseController;
import com.gopay.webtest.util.BaseSign;
import com.gopay.webtest.util.ReflectUtil;
import com.gopay.webtest.vo.ExPayApiConfirmInfo;
import com.gopay.webtest.vo.ExPayApiInfo;
import com.gopay.webtest.vo.PayInfo;
import com.gopay.webtest.vo.entrustpay.ContractInfoVO;
import com.gopay.webtest.xml.XmlDao;

/**
 * 委托授权（申请/确认）
 * EntrustContractController.java
 * @author zhuliang
 * @2016年12月21日 下午16:09:27  www.gopay.com.cn Inc.All rights reserved.
 */
@Controller
@RequestMapping("/contract")
public class EntrustContractController extends BaseController {

    private static final String CHARSET_GBK = "1";
    
    @Resource(name = "paySignHandler")
    private BaseSign paySignHandler;
    
    private static Map<String, String> map = null;
    
    @Autowired
    public EntrustContractController(@Qualifier(value = "xmlDao") XmlDao xmlDao) {
        try {
            map = xmlDao.readData4Map("contractApply", "contractApply");
            map = xmlDao.readData4Map("contractConfirm", "contractConfirm");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 跳转到首页面
     * @param flag
     * @return
     */
    @RequestMapping("/contractApplyIndex")
    public ModelAndView applyIndex(String flag) {
        ModelAndView mav = new ModelAndView();
        ContractInfoVO contractInfo = getDefaultInfoFromXML();
        mav.setViewName("gopay.webtest.contract.apply");
        mav.addObject("contractInfo", contractInfo);
        return mav;
    } 
    
    /**
     * 跳转到首页面
     * @param flag
     * @return
     */
    @RequestMapping("/contractConfirmIndex")
    public ModelAndView confirmIndex(String flag) {
        ModelAndView mav = new ModelAndView();
        ContractInfoVO contractInfo = getDefaultInfoFromXML();
        mav.setViewName("gopay.webtest.contract.confirm");
        mav.addObject("contractInfo", contractInfo);
        return mav;
    } 
    
    private ContractInfoVO getDefaultInfoFromXML() {
    	ContractInfoVO contractInfo = new ContractInfoVO();

    	contractInfo.setMerchantID((String) map.get("merchantID"));
    	contractInfo.setTranDateTime(com.gopay.webtest.util.DateUtils.date2string(new Date(),
                com.gopay.webtest.util.DateUtils.DEFAULT_PATTERN));
    	contractInfo.setGopayServerTime(com.gopay.webtest.util.DateUtils.date2string(new Date(),
                com.gopay.webtest.util.DateUtils.DEFAULT_PATTERN));
    	contractInfo.setVirCardNoIn((String) map.get("virCardNoIn"));

        return contractInfo;
    } 
    

    
    /**
     * 提交订单到支付宝
     * 
     * @param payInfo
     * @return
     */
    @RequestMapping("/contractApplySubmit")
    public ModelAndView paySubmit(ContractInfoVO contractInfo) {
        ModelAndView mav = new ModelAndView();      
        StopWatch sw  = new StopWatch();
        
        // 设置MD5加密字段
        try {
            sw.start();
            paySignHandler.sign(contractInfo.getTranCode() + "_" + contractInfo.getVersion(), "signType", "signValue", contractInfo, getRequest());
            sw.stop();
            logger.info("step1 time:"+sw.getTime());
            logger.info("后台notify密文值:" + contractInfo.getSignValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        //封装参数  明文验签，密文上送
        Map<String, String> paramMap = new HashMap<>();
        
        desField(contractInfo, paramMap, contractInfo.getVerficationCode());
        
        
        String signedValue = contractInfo.getSignValue();
        if (null == signedValue) {
            // 加密操作失败,置返回码为身份认证md5加密失败
        	contractInfo.setRespCode("MR08");
            mav.setViewName("gopay.webtest.wxPay");
        } else {
            if (!contractInfo.getCharset().equals("2")) {
                mav.setViewName("gopay.webtest.contractApplyFormSubmitGbk");
            } else {
                mav.setViewName("gopay.webtest.contractApplyFormSubmitUtf8");
            }
        }
        mav.addObject("contractInfo", contractInfo);
        return mav;
    }

    
    /**
     * 提交订单到支付宝
     * 
     * @param payInfo
     * @return
     */
    @RequestMapping("/contractConfirmSubmit")
    public ModelAndView confirmSubmit(ContractInfoVO contractInfo) { 
        ModelAndView mav = new ModelAndView();      
        StopWatch sw  = new StopWatch();
        
        // 设置MD5加密字段
        try {
            sw.start();
            paySignHandler.sign(contractInfo.getTranCode() + "_" + contractInfo.getVersion(), "signType", "signValue", contractInfo, getRequest());
            sw.stop();
            logger.info("step1 time:"+sw.getTime());
            logger.info("后台notify密文值:" + contractInfo.getSignValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        //封装参数  明文验签，密文上送
        Map<String, String> paramMap = new HashMap<>();
        
        desField(contractInfo, paramMap, contractInfo.getVerficationCode());
        
        
        String signedValue = contractInfo.getSignValue();
        if (null == signedValue) {
            // 加密操作失败,置返回码为身份认证md5加密失败
        	contractInfo.setRespCode("MR08");
            mav.setViewName("gopay.webtest.wxPay");
        } else {
            if (!contractInfo.getCharset().equals("2")) {
                mav.setViewName("gopay.webtest.contractConfirmFormSubmitGbk");
            } else {
                mav.setViewName("gopay.webtest.contractConfirmFormSubmitUtf8");
            }
        }
        mav.addObject("contractInfo", contractInfo);
        return mav;
    }
    

    /**
     * 跳转到确认支付页面
     * @param payInfo
     * @return
     */
    @RequestMapping(value = "/apiConfirm")
    public ModelAndView apiConfirm(ExPayApiInfo payInfo) {
        
        ModelAndView mav = new ModelAndView();
        
        payInfo.setGopayServerTime(com.gopay.webtest.util.DateUtils.date2string(new Date(), com.gopay.webtest.util.DateUtils.DEFAULT_PATTERN));
        
        /*if (StringUtils.equals(payInfo.getTranCode(), "8803")) {
           // mav.setViewName("gopay.webtest.expay.dkConfirm");
        } else {
            
        }*/
        mav.setViewName("gopay.webtest.expaynew.apiConfirm");
        mav.addObject("payInfo", payInfo);
        
        return mav;
    }
    
    /**
     * 确认支付 ajax调用
     * @param payInfo
     * @return
     */
   // @ResponseBody
    @RequestMapping(value = "/apiConfirmSubmit")
    public ModelAndView paySubmitConfirm(ExPayApiConfirmInfo payInfo, HttpServletRequest request) {
        
        // 设置MD5加密字段
        try {
            paySignHandler.sign(payInfo.getTranCode() + "_" + payInfo.getVersion(), "signType", "signValue", payInfo, request);
            logger.info("8802 快捷api 密文值:" + payInfo.getSignValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
      //封装参数
        Map<String, String> paramMap = new HashMap<>();
        
        desField(payInfo, paramMap, payInfo.getVerficationCode());
        
        /*String xml = getXml(payInfo.getCharset(), paramMap, request);
        
      //解析返回的xml文件
        
        JSONObject js = new JSONObject();
        
        try {
            Document doc  = DocumentHelper.parseText(xml);
            
            Node el = doc.selectSingleNode("/GopayTranRes/respCode");
            
            String respCode = el.getStringValue();
            js.put("respCode", respCode);
            if (!"0000".equals(respCode)) {
                el = doc.selectSingleNode("/GopayTranRes/respMessage");
                js.put("respMessage", el.getStringValue());
            }
            
            js.put("xml", xml);
            
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return js.toString();*/
        ModelAndView mv = new ModelAndView();
        if (!payInfo.getCharset().equals("2")) {
            mv.setViewName("gopay.webtest.expaynew.formsubmit8802gbk");
        } else {
            mv.setViewName("gopay.webtest.expaynew.formsubmit8802utf8");
        }
        mv.addObject("payInfo", payInfo);
        
        return mv;
        
    }

    /**
     * 加密字段.
     * @param info
     * @param paramMap
     * @param vcode
     */
    private void desField(Object info, Map<String, String> paramMap, String vcode) {
        
        try {
            //字段加密
            ReflectUtil.desField(info, vcode);
            ReflectUtil.copyFiledToMap(info, paramMap);
            paramMap.remove("verficationCode");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    

}
